package com.zjh.springsecuritysplitverifycode.controller;

import com.google.code.kaptcha.Producer;
import lombok.RequiredArgsConstructor;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
@RequiredArgsConstructor
public class VerifyController {

    private final Producer producer;

    @RequestMapping("/verify")
    public String  verify(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        //1.生成验证码
        String verifyCode = producer.createText();
        //2.保存到中 session
        session.setAttribute("kaptcha", verifyCode);
        //3.生成图片
        BufferedImage bi = producer.createImage(verifyCode);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(bi, "png", byteArrayOutputStream);
        byte[] by = byteArrayOutputStream.toByteArray();
        //4.响应图片
        return "data:image/png;base64," + Base64.encodeBase64String(by);
    }

}
